<!-- 新增编辑呈批件 -->
<template>
  <div class="app-container" :style="height">
    <el-form  ref="form"  class="work-search-form" :model="form" :rules="rules" label-width="80px">
        <el-row>
            <el-col span="12">
                <el-form-item label="部门" prop="pressing">
                    <el-select v-model="form.pressing" placeholder="请选择部门"> 
                    <el-option-
                        v-for="dict in degreeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col span="12">
                <el-form-item label="订单" prop="pressing">
                    <el-select v-model="form.pressing" placeholder="请选择订单">
                    <el-option
                        v-for="dict in degreeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col span="12">
                <el-form-item label="归属大类" prop="pressing">
                    <el-select v-model="form.pressing" placeholder="请选择归属大类">
                    <el-option
                        v-for="dict in degreeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col span="12">
                 <el-form-item label="归属小类" prop="pressing">
                    <el-select v-model="form.pressing" placeholder="请选择归属小类">
                    <el-option
                        v-for="dict in degreeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        
       <el-row>
            <el-col span="12">
                <el-form-item label="金额" prop="title">
                    <el-input v-model="form.title" placeholder="请输入标题" />
                </el-form-item>
            </el-col>
            <el-col span="12">
                <el-form-item label="时间" prop="number" >
                    <el-input v-model="form.number" placeholder="请输入编号" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col span="12">
                <el-form-item label="名称" >
                    <el-input v-model="userInfo.dept.deptName" placeholder="" :disabled="true" />
                </el-form-item>
            </el-col>
            <el-col span="12">
                <el-form-item label="数量">
                    <el-input v-model="userInfo.employeeNum" placeholder="" :disabled="true" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col span="12">
                <el-form-item label="单价" >
                    <el-input v-model="userInfo.dept.deptName" placeholder="" :disabled="true" />
                </el-form-item>
            </el-col>
            <el-col span="12">
                <el-form-item label="总价">
                    <el-input v-model="userInfo.employeeNum" placeholder="" :disabled="true" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item label="说明" prop="remark" style="width: 50%;">
            <el-input type="textarea" v-model="form.remark" placeholder="请填写备注" />
        </el-form-item>
        <el-form-item label="附件">
        <el-upload
            ref="upload"
            :action="upload.url"
            :headers="upload.headers"
            multiple
            :file-list="upload.fileList"
            :on-success="annexSuccess"
            :before-upload="beforeAttachmentUpload"
            :before-remove="beforeRemove"
            :on-remove="annexRemove">
            <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
            <div slot="tip" style="color: #999; font-size: 12px;"
            v-text="'支持'+fileUploadParams.fileType+'，且不超过'+fileUploadParams.fileSize+'MB'"></div>
        </el-upload>
        </el-form-item>
        <el-form-item label="审批流程">
        <el-steps :active="1" simple>
        <el-step title="步骤 1" icon="el-icon-edit"></el-step>
        <el-step title="步骤 2" icon="el-icon-upload"></el-step>
        <el-step title="步骤 3" icon="el-icon-picture"></el-step>
        </el-steps>
        </el-form-item>
    </el-form>
    
    </el-row>
    <div slot="footer" class="dialog-footer" style="text-align:center">
      <!-- <el-button type="primary" @click="printTable">打 印</el-button> -->
      <template v-if="!params.isEdit">
        <el-button type="primary" :loading="submitLoading" @click="submitForm(1)">提 交</el-button>
      </template>
      <el-button type="primary" :loading="submitLoading" @click="submitForm(2)">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
  import {addApprovalDoc,detailsApprovalDoc,addEditApprovalDoc } from "@/api/system/approvalDocManage";
  import Editor from '@/components/Editor';
  import { getToken } from "@/utils/auth";
  import { fileUploadParams,getFileNameSuffix } from "@/utils/ruoyi"

  export default {
    name: "AddEditDoc",
    components: {
      Editor
    },
    data() {
      return {
        height: "max-height:"+((document.documentElement.clientHeight || document.body.clientHeight)-110)+"px;overflow-y:auto",
        params: {
          isEdit: false,
        },
        form: {},
        fileUploadParams: fileUploadParams(),
        userInfo: JSON.parse(this.$store.getters.userInfo),
        // 缓急程度数据字典
        degreeOptions: [],
        // 密级数据字典
        secretLevelOptions: [],
        //部门列表
        deptList: [],
        // 部门列表
        menuOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          title: [
            { required: true, message: "请输入标题", trigger: "blur" }
          ],
          number: [
            { required: true, message: "请输入编号", trigger: "blur" }
          ],
          pressing: [
            { required: true, message: "请选择缓急程度", trigger: "change" }
          ],
          security: [
            { required: true, message: "请选择密级", trigger: "change" }
          ],
        },
        upload: {
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: []
        },
        //表单提交加载项
        submitLoading: false
      }
    },
    created() {
      if(this.$route.params && this.$route.params.docId>0){
        this.$route.meta.title = '编辑呈批件'
        this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path)].title = '编辑呈批件'
      }else{
        this.$route.meta.title = '新建呈批件'
        this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path)].title = '新建呈批件'
      }
      this.reset();
      const id = this.$route.params && this.$route.params.docId;
      this.params = this.$route.params;
      if(id && id > 0){
        detailsApprovalDoc({id:id}).then((res)=>{
          this.form = res.data
          //获取文件列表数据
          this.$nextTick(() => {
            const arr = [];
            if (this.form.attachmentName != null){
              var attachmentName = this.form.attachmentName.split(",");
              var attachmentUrl = this.form.attachmentUrl.split(",");
              var attachmentPath = this.form.attachmentPath.split(",");
              for (var k=0;k<attachmentName.length;k++){
                arr.push({
                  name:attachmentName[k],
                  response:{
                    fileName:attachmentPath[k],
                    url:attachmentUrl[k],
                  }
                });
              }
            }
            this.upload.fileList=arr;
            this.form.fileList=arr;
          });
          this.$nextTick(()=>{
            this.$refs['form'].clearValidate()
          })
          console.log(this.form)
        })
      }
      this.getDicts("degree_urgency").then(response => {
        this.degreeOptions = response.data;
      });
      this.getDicts("secret_level").then(response => {
        this.secretLevelOptions = response.data;
      });
      this.getMenuTreeselect();
      // if (row!=null && row!=undefined && row!=''){
      //   this.form = row;
      //   this.form.announcementType = ''+this.form.announcementType+'';
      //   this.$nextTick(() => {
      //     const arr = [];
      //     if (this.form.receiveUserId != null){
      //       var userids = this.form.receiveUserId.split(",");
      //       for (var k=0;k<userids.length;k++){
      //         arr.push(parseInt(userids[k]));
      //       }
      //     }
      //     this.$refs.menu.setCheckedKeys(userids);//获取已经设置的资源后渲染
      //   });
      //   this.$nextTick(() => {
      //     const arr = [];
      //     if (row.attachmentName != null){
      //       var attachmentName = row.attachmentName.split(",");
      //       var attachmentUrl = row.attachmentUrl.split(",");
      //       var attachmentPath = row.attachmentPath.split(",");
      //       for (var k=0;k<attachmentName.length;k++){
      //         arr.push({
      //           name:attachmentName[k],
      //           response:{
      //             fileName:attachmentPath[k],
      //             url:attachmentUrl[k],
      //           }
      //         });
      //       }
      //     }
      //     this.upload.fileList=arr;
      //     this.form.fileList=arr;
      //   });
      // }
    },
    methods: {
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.form = {
          id: undefined,
          title: undefined,
          number: undefined,
          pressing: undefined,
          security: undefined,
          remark: undefined,
          applyDepartment: this.userInfo.dept.deptId,
          fileList: [],
        };
        this.upload.fileList = [];
        this.resetForm("form");
        this.$nextTick(()=>{
          this.$refs['form'].clearValidate()
        })
      },
      // 取消按钮
      cancel() {
        this.$router.go(-1);// 返回
        //关闭子页面
        this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1);
        var view = {
          name: 'ApprovalDocManage',
        }
        this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
          this.$router.push({
            name: 'ApprovalDocManage'
          });
        })
      },
      /** 提交按钮 */
      submitForm:function(statu) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(statu == 1){
              //提交并启动流程
              this.submitLoading = true
              addApprovalDoc(this.form).then((res)=>{
                this.submitLoading = false
                if (res.code === 200) {
                  this.msgSuccess("新增并启动流程成功");
                  this.cancel();
                }
              }).catch(()=>{
                this.submitLoading = false
              });
            }else if(statu == 2){
              //保存新增/编辑
              this.submitLoading = true
              addEditApprovalDoc(this.form).then(res => {
                this.submitLoading = false
                if (res.code === 200) {
                  this.msgSuccess("保存成功");
                  this.cancel();
                }
              }).catch(()=>{
                this.submitLoading = false
              });
            }
          }
        });
      },
      // 跳转到打印单页面
      printTable(){
        this.$store.dispatch('tagsView/delView', {'name':'PrintApprovalDoc'}).then(({ visitedViews }) => {
          this.$router.push({
            name: 'PrintApprovalDoc'
          });
        })
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.msgSuccess(response.msg);
        this.$alert(response.url, '视频地址', {
          dangerouslyUseHTMLString: true
        });
      },
      // 附件上传成功处理
      annexSuccess(response, file, fileList) {
        console.log('附件上传成功处理')
        console.log(response)
        console.log(file)
        console.log(fileList)
        this.form.fileList=fileList
      },
      // 上传之前的处理
      beforeAttachmentUpload(file, fileList){
        var isTrue = true
        var fileTypeVerify = this.fileUploadParams.fileType
        var fileSuffix = getFileNameSuffix(file)
        if(fileTypeVerify.indexOf(fileSuffix) > -1){
          isTrue = true
        }else{
          this.msgError('支持'+this.fileUploadParams.fileType+'，且不超过'+this.fileUploadParams.fileSize+'MB')
          isTrue = false
        }
        return isTrue;
      },
      //移除文件之前的处理
      beforeRemove(file, fileList){
        let a = true;
        if (file && file.status==="success") {
            a = this.$confirm(`确定移除 ${ file.name }？`);
        }
        return a;
      },
      // 附件上传移除
      annexRemove(file, fileList) {
        console.log(fileList)
        if(file && file.status == "success"){
          this.form.fileList=fileList
          var arr = []
          var arr2 = []
          console.log(this.upload.fileList)
          console.log(this.form.fileList)
          // this.upload.fileList=arr;
          // this.form.fileList=arr;
          // for(var i=0;i<this.form.enclosure_url.length;i++){
          //   if(file.uid != this.form.enclosure_url[i].uid){
          //     arr.push(this.form.enclosure_url[i])
          //     arr2.push(this.form.enclosureUrl[i])
          //   }
          // }
          // this.form.enclosureUrl = arr2
          // this.form.enclosure_url = arr
        }
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        // treeselect().then(response => {
        //   this.menuOptions = response.data;
        // });
      },
      // 所有人员节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.announcementType);
      },
    }
  }
</script>
